package com.ruoyi.common.utils.file;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author qbf
 * excel导入工具
 */
public class ExcelImporter {

    public static List<List<String>> importExcel(MultipartFile file) throws IOException {
        List<List<String>> userInfoList = new ArrayList<>();
        try (InputStream fis = file.getInputStream();
             Workbook workbook = new XSSFWorkbook(fis)) {
            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);
            Iterator<Row> rowIterator = sheet.iterator();

            // 跳过标题行
            if (rowIterator.hasNext()) rowIterator.next();

            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                List<String> info = new ArrayList<>();

                short start = row.getFirstCellNum();
                short end = row.getLastCellNum();

                for(short i=start; i<end; i++){
                    info.add(getValueAsString(row.getCell(i)));
                }

                userInfoList.add(info);
            }
        }
        return userInfoList;
    }

    private static String getValueAsString(Cell cell) {
        if (cell == null) return "";
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                return parseNumber(cell);
            default:
                return "";
        }
    }

    private static String parseNumber(Cell cell) {
        // 如果是数值类型，则按数字处理
        double numericValue = cell.getNumericCellValue();
        // 检查是否为整数
        if (numericValue == Math.floor(numericValue) && !Double.isInfinite(numericValue)) {
            long intValue = (long) numericValue;
            return intValue+"";
        } else {
            return new BigDecimal(numericValue).toPlainString();
        }
    }
}
